////////////////////////////////////////
// StringTable.cpp
/* Name: Stephen Durfey
 * Class: cs335
 * Prof: Dr. Michael Poor
 * Due Date: October 17, 2008
 ****************************************/
#include <vector>

#include "StringTable.h"
using namespace std;

////////////////////////////////////////

StringTable::StringTable(ifstream & infile)
{
    string          s;

    while (readMultiWord(s, infile))  // not end of file
    {
        vector<string>* vectPtr = new vector<string>();
        do
        {
            vectPtr->push_back(s);
        }
        while (readMultiWord(s, infile));
        
        if(table.empty())
            table.push_back(vectPtr);
        else
            insertInAlphaOrder(vectPtr);
    }
}



int StringTable::rows() const
{
    return table.size();
}

//returns the dereferenced value in the specified row

const vector<string> & StringTable::operator[](int i) const
{
    return *table[i];
}

void StringTable::insertInAlphaOrder(vector<string>* vectPtr)
{
    vector<vector<string>* >::iterator colIter = table.begin();
    vector<string>::iterator rowIter;
    bool inserted = false;
    
    while(!inserted && colIter < table.end())
    {
        rowIter = (*colIter)->begin();
        //compares value of string in element 0 of vectPtr to the first
        //element of the non-empty vector table. 
        if(*(vectPtr->begin()) > *rowIter)
            colIter++;
        
        //is true if 1st element of vectPtr is < or == to first element
        //already stored in the table vector
        else
        {
            //inserts the vectPtr in the position just before the location
            //that is < or == vectPtr.
            table.insert(colIter, vectPtr);
            inserted = true;
        }        
    }
    //if iterator made it to the end of the vector without being less than
    //vectPtr, it is the largest lexographically, so push_back()
    if(colIter == table.end())
        table.push_back(vectPtr);
}

